package com.example.ylsys.plants.view;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.ylsys.plants.R;
import com.example.ylsys.plants.Utils.Base64Utils;
import com.example.ylsys.plants.Utils.BasicToolUtils;
import com.example.ylsys.plants.Utils.RSAUtils;
import com.example.ylsys.plants.Utils.SystemUtil;
import com.example.ylsys.plants.Utils.ToastUtils;
import com.example.ylsys.plants.base.BaseMvpActivity;
import com.example.ylsys.plants.base.MyApplication;
import com.example.ylsys.plants.bean.BackResultBean;
import com.example.ylsys.plants.bean.LoginParamsBean;
import com.example.ylsys.plants.contract.LoginDialogContract;
import com.example.ylsys.plants.presenter.LoginDialogPresenter;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static com.example.ylsys.plants.Utils.AesUtils.generateKey;
import static com.example.ylsys.plants.Utils.BasicToolUtils.GetSignature;
import static com.example.ylsys.plants.Utils.BasicToolUtils.getTime;
import static com.example.ylsys.plants.Utils.RSAUtils.PUCLIC_KEY;

public class LoginDialogActivity extends BaseMvpActivity<LoginDialogPresenter> implements LoginDialogContract.View{

    @BindView(R.id.user_name) EditText mEtdName;
    @BindView(R.id.etd_tel) EditText mEtdTel;
    @BindView(R.id.user_pwd) EditText mEtdPwd;
    @BindView(R.id.etd_authcode) EditText mEtdAuthcode;
    @BindView(R.id.cb_show_hide_pwd) CheckBox mCbShowHidePwd;
    @BindView(R.id.btn_get_authcode) Button mBtnGetAuthcode;
    @BindView(R.id.btn_login) Button mBtnLogin;
    LoginParamsBean userParams;
    String action="sendsms";


    @Override
    public int getLayoutId() {
        return R.layout.activity_login_dialog;
    }

    @Override
    public void initView() {
        mPresenter = new LoginDialogPresenter();
        mPresenter.attachView(this);
    }

    /**
     * @return 帐号
     */
    private String getUsername() {
        return mEtdName.getText().toString().trim();
    }

    /**
     * @return 密码
     */
    private String getPassword() {
        return mEtdPwd.getText().toString().trim();
    }

    /**
     * @return 手机号
     */
    private String getTel() {
        return mEtdTel.getText().toString().trim();
    }

    /**
     * @return 验证码
     */
    private String getAuthcode() {
        return mEtdAuthcode.getText().toString().trim();
    }


    @OnClick({R.id.btn_get_authcode,R.id.btn_login})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.btn_login:
                if (getUsername().isEmpty() || getPassword().isEmpty()|| getTel().isEmpty()||getAuthcode().isEmpty()) {
                        ToastUtils.showShort(this,"账号密码验证码不能为空");
                        return; }else {
                    String action="bindtel";
                    get_userParams();
                    Map<String,String> post_Params=get_PostParams(action);
                    Map<String,String> url_Params=get_urlParams(action);
                    //相对于获取验证码步骤
                    //url action改为bindtel
                    //post数据增加smscode
                    mPresenter.login(url_Params,post_Params);
                }
                break;

            case R.id.btn_get_authcode:
                if (getUsername().isEmpty() || getPassword().isEmpty()|| getTel().isEmpty()) {
                    ToastUtils.showShort(this,"短信验证码不能为空");
                    return; }else {
                    String action="sendsms";
                    get_userParams();
                    Map<String,String> post_Params=get_PostParams(action);
                    mPresenter.getAc(get_urlParams(action),post_Params);
                }
                break;
        }
    }

    @OnCheckedChanged(R.id.cb_show_hide_pwd)
    public void onCheckedChanged(CheckBox checkBox){
        if(checkBox.isChecked()){
            mEtdPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }else {
            mEtdPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    @Override
    public void getAcOnSuccess(BackResultBean backResultBean) {
        Toast.makeText(LoginDialogActivity.this,backResultBean.getResult(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void loginOnSuccess(String result) {
        Toast.makeText(LoginDialogActivity.this, result, Toast.LENGTH_SHORT).show();
        String EtdAuthcode =  mEtdAuthcode.getText().toString();
        String Md5Secret =BasicToolUtils.md5(EtdAuthcode);
        userParams.setCypher(get_encrypt(Md5Secret));
        mPresenter.SaveData(userParams,this);
        Intent intent=new Intent(LoginDialogActivity.this,WelcomingActivity.class);
        startActivity(intent);
        finish();
    }



    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {
        ToastUtils.showShort(this,"验证码错误");
    }

    private void get_userParams(){
        userParams=new LoginParamsBean();
        userParams.setClientid(SystemUtil.getIMEI(this));
        userParams.setUserName(mEtdName.getText().toString());
        userParams.setPassword(mEtdPwd.getText().toString());
        userParams.setTel(mEtdTel.getText().toString());
        userParams.setNonce(generateKey());
    }

    /**
     * @return 需要post的列表
     */
    private Map<String,String> get_PostParams(String action){

        Map<String,String> paras=new HashMap<String, String>();
        paras.put("clientid",userParams.getClientid());
        paras.put("userName",userParams.getUserName());
        paras.put("password",userParams.getPassword());
        paras.put("tel",userParams.getTel());
        if (action=="bindtel"){
            paras.put("smscode",mEtdAuthcode.getText().toString());

        }
        return paras;
    }




    /**
     * @return 生成signature的字段
     */
    private Map<String,String> get_signParams(String action){

        Map<String,String> paras=new HashMap<String, String>();
        paras.put("nonce",userParams.getNonce());
        paras.put("clientid",userParams.getClientid());
        paras.put("timestamp",getTime());
        paras.put("tel",userParams.getTel());
        paras.put("action",action);
        if (action.equals("bindtel")){
            paras.put("smscode",getAuthcode());
        }
        return paras;
    }

    /**
     * @param
     * @return 生成url的字段
     */
    private Map<String,String> get_urlParams(String action){
        String signature = null;
        try {
            //仍然使用用户输入的密码生成signature
            signature = GetSignature(userParams.getPassword(),get_signParams(action));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,String> paras=new HashMap<String, String>();
        paras.put("nonce",userParams.getNonce());
        paras.put("timestamp",getTime());
        paras.put("signature",signature);
        paras.put("action",action);
        return paras;
    }


    private String get_encrypt(String str){
        String afterencrypt=null;
        try {
            // 从字符串中得到公钥
            PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
            // 加密
            byte[] encryptByte = RSAUtils.encryptData(str.getBytes(), publicKey);
            // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
            afterencrypt = Base64Utils.encode(encryptByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return afterencrypt;
    }
}
